<!-- 商品发布 - 基础设置 -->
<template>
  <el-form ref="formRef" :disabled="isDetail" :model="formData" :rules="rules" label-width="120px">
    <el-form-item label="商品名称" prop="name">
      <el-input
        v-model="formData.name"
        :autosize="{ minRows: 2, maxRows: 2 }"
        :clearable="true"
        :show-word-limit="true"
        class="w-80!"
        maxlength="64"
        placeholder="请输入商品名称"
        type="textarea"
      />
    </el-form-item>
    <el-form-item label="商品分类" prop="categoryId">
      <el-cascader
        v-if="categoryList.length > 0"
        v-model="formData.categoryId"
        :options="categoryList"
        :props="defaultProps"
        class="w-80"
        clearable
        filterable
        placeholder="请选择商品分类"
        :show-all-levels="true"
      />
      <el-alert
        v-else
        title="未找到车辆服务分类，请联系管理员检查分类配置"
        type="warning"
        :closable="false"
        show-icon
      />

    </el-form-item>
    <el-form-item label="商品品牌" prop="brandId">
      <el-select v-model="formData.brandId" class="w-80" placeholder="请选择商品品牌">
        <el-option
          v-for="item in brandList"
          :key="item.id"
          :label="item.name"
          :value="item.id as number"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="商品关键字" prop="keyword">
      <el-input v-model="formData.keyword" class="w-80!" placeholder="请输入商品关键字" />
    </el-form-item>
    <el-form-item label="商品简介" prop="introduction">
      <el-input
        v-model="formData.introduction"
        :autosize="{ minRows: 2, maxRows: 2 }"
        :clearable="true"
        :show-word-limit="true"
        class="w-80!"
        maxlength="128"
        placeholder="请输入商品简介"
        type="textarea"
      />
    </el-form-item>
    <el-form-item label="商品封面图" prop="picUrl">
      <UploadImg v-model="formData.picUrl" :disabled="isDetail" height="80px" />
    </el-form-item>
    <el-form-item label="商品轮播图" prop="sliderPicUrls">
      <UploadImgs v-model="formData.sliderPicUrls" :disabled="isDetail" />
    </el-form-item>
  </el-form>
</template>
<script lang="ts" setup>
import { PropType } from 'vue'
import { copyValueToTarget } from '@/utils'
import { propTypes } from '@/utils/propTypes'
import { defaultProps, handleTree } from '@/utils/tree'
import type { Spu } from '@/api/mall/product/carrent'
import * as ProductCategoryApi from '@/api/mall/product/category'
import * as ProductBrandApi from '@/api/mall/product/brand'
import { BrandVO } from '@/api/mall/product/brand'

defineOptions({ name: 'ProductSpuInfoForm' })
const props = defineProps({
  propFormData: {
    type: Object as PropType<Spu>,
    default: () => {}
  },
  isDetail: propTypes.bool.def(false) // 是否作为详情组件
})

const message = useMessage() // 消息弹窗

const formRef = ref() // 表单 Ref
const formData = reactive<Spu>({
  name: '', // 商品名称
  categoryId: undefined, // 商品分类
  keyword: '', // 关键字
  picUrl: '', // 商品封面图
  sliderPicUrls: [], // 商品轮播图
  introduction: '', // 商品简介
  brandId: undefined // 商品品牌
})
const rules = reactive({
  name: [required],
  categoryId: [required],
  keyword: [required],
  introduction: [required],
  picUrl: [required],
  sliderPicUrls: [required],
  brandId: [required]
})

/** 将传进来的值赋值给 formData */
watch(
  () => props.propFormData,
  (data) => {
    if (!data) {
      return
    }
    copyValueToTarget(formData, data)
  },
  {
    immediate: true
  }
)

/** 表单校验 */
const emit = defineEmits(['update:activeName'])
const validate = async () => {
  if (!formRef) return
  try {
    await unref(formRef)?.validate()
    // 校验通过更新数据
    Object.assign(props.propFormData, formData)
  } catch (e) {
    message.error('【基础设置】不完善，请填写相关信息')
    emit('update:activeName', 'info')
    throw e // 目的截断之后的校验
  }
}
defineExpose({ validate })

/** 初始化 */
const brandList = ref<BrandVO[]>([]) // 商品品牌列表
const categoryList = ref<any[]>([]) // 商品分类树（使用any类型因为handleTree会添加children属性）

/**
 * 过滤车辆服务相关的分类
 * 只显示车辆服务及其子分类，屏蔽其他所有分类
 */
const filterVehicleServiceCategories = (categories: any[]): any[] => {
  console.log('=== 汽车商品添加页面 - 开始过滤车辆服务分类 ===')
  console.log('原始分类数量:', categories.length)

  // 打印所有原始分类用于调试
  categories.forEach(category => {
    console.log(`原始分类: [${category.id}] ${category.name}, parentId: ${category.parentId}`)
    if (category.children && category.children.length > 0) {
      category.children.forEach((child: any) => {
        console.log(`  └─ 子分类: [${child.id}] ${child.name}, parentId: ${child.parentId}`)
        if (child.children && child.children.length > 0) {
          child.children.forEach((grandChild: any) => {
            console.log(`    └─ 孙分类: [${grandChild.id}] ${grandChild.name}, parentId: ${grandChild.parentId}`)
          })
        }
      })
    }
  })

  // 车辆服务相关的分类ID和名称
  const VEHICLE_SERVICE_PARENT_ID = 86 // 车辆服务父分类ID
  const VEHICLE_SERVICE_NAMES = ['车辆服务', '汽车服务', '车辆', '汽车']

  /**
   * 递归查找车辆服务分类并保留其完整结构
   */
  const findVehicleServiceCategory = (categoryList: any[]): any | null => {
    for (const category of categoryList) {
      // 直接匹配车辆服务分类ID
      if (category.id === VEHICLE_SERVICE_PARENT_ID) {
        console.log(`✓ 通过ID找到车辆服务分类: [${category.id}] ${category.name}`)
        console.log(`车辆服务分类的子分类数量: ${category.children?.length || 0}`)

        // 打印子分类详情
        if (category.children && category.children.length > 0) {
          console.log('车辆服务子分类详情:')
          category.children.forEach((child: any, index: number) => {
            console.log(`  ${index + 1}. [${child.id}] ${child.name}`)
          })
        }

        return category
      }

      // 匹配名称
      if (VEHICLE_SERVICE_NAMES.some(name => category.name?.includes(name))) {
        console.log(`✓ 通过名称找到车辆服务分类: [${category.id}] ${category.name}`)
        console.log(`车辆服务分类的子分类数量: ${category.children?.length || 0}`)
        return category
      }

      // 递归查找子分类
      if (category.children && category.children.length > 0) {
        const found = findVehicleServiceCategory(category.children)
        if (found) {
          return found
        }
      }
    }
    return null
  }

  // 查找车辆服务分类
  const vehicleServiceCategory = findVehicleServiceCategory(categories)

  if (vehicleServiceCategory) {
    console.log(`🎯 成功找到车辆服务分类: [${vehicleServiceCategory.id}] ${vehicleServiceCategory.name}`)

    // 确保级联选择器的正确格式，保留完整的子分类结构
    const formatCategoryForCascader = (category: any): any => {
      console.log(`格式化分类: [${category.id}] ${category.name}, 子分类数量: ${category.children?.length || 0}`)

      const formatted = {
        id: category.id,
        name: category.name,
        parentId: category.parentId,
        children: []
      }

      // 递归格式化子分类
      if (category.children && category.children.length > 0) {
        console.log(`处理 [${category.id}] ${category.name} 的 ${category.children.length} 个子分类`)
        formatted.children = category.children.map((child: any) => {
          console.log(`  处理子分类: [${child.id}] ${child.name}`)
          return formatCategoryForCascader(child)
        })
        console.log(`[${category.id}] ${category.name} 格式化后的子分类数量: ${formatted.children.length}`)
      } else {
        console.log(`[${category.id}] ${category.name} 没有子分类`)
      }

      return formatted
    }

    const result = [formatCategoryForCascader(vehicleServiceCategory)]

    console.log('✅ 汽车商品添加页面 - 过滤完成，只保留车辆服务分类及其子分类')
    console.log('最终分类结构:', JSON.stringify(result, null, 2))

    return result
  } else {
    console.error('❌ 汽车商品添加页面 - 没有找到车辆服务分类')

    // 备用方案：创建一个默认的车辆服务分类
    console.log('🔧 汽车商品添加页面 - 启用备用方案：创建默认车辆服务分类')
    const defaultCategory = {
      id: 86,
      name: '车辆服务',
      parentId: 0,
      children: [
        { id: 84, name: '车辆租赁', parentId: 86, children: [] },
        { id: 85, name: '车辆售卖', parentId: 86, children: [] }
      ]
    }

    return [defaultCategory]
  }
}



onMounted(async () => {
  console.log('=== 汽车商品添加页面 - 开始初始化 ===')

  // 获得分类树
  const data = await ProductCategoryApi.getCategoryList({})
  console.log('API返回的原始分类数据数量:', data.length)

  const fullCategoryTree = handleTree(data, 'id', 'parentId')
  console.log('构建的完整分类树数量:', fullCategoryTree.length)

  // 过滤车辆服务分类
  categoryList.value = filterVehicleServiceCategories(fullCategoryTree)

  // 验证过滤结果
  console.log('=== 汽车商品添加页面 - 最终结果 ===')
  console.log('分类选项数量:', categoryList.value.length)

  if (categoryList.value.length === 1) {
    const category = categoryList.value[0]
    console.log('✅ 汽车商品添加页面 - 显示车辆服务分类:', category.name)
    console.log('车辆服务子分类数量:', category.children?.length || 0)

    if (category.children && category.children.length > 0) {
      console.log('车辆服务子分类列表:')
      category.children.forEach((child: any, index: number) => {
        console.log(`  ${index + 1}. [${child.id}] ${child.name}`)
      })
    }

    console.log('🎉 汽车商品添加页面 - 车辆服务分类过滤成功！')
  } else if (categoryList.value.length === 0) {
    console.error('❌ 汽车商品添加页面 - 没有分类选项')
  } else {
    console.warn('⚠️ 汽车商品添加页面 - 分类选项过多:', categoryList.value.length)
    categoryList.value.forEach((cat, index) => {
      console.log(`${index + 1}. [${cat.id}] ${cat.name}`)
    })
  }

  // 自动设置默认分类为车辆出租（ID=84）
  if (!formData.categoryId && categoryList.value.length > 0) {
    // 查找车辆出租分类（ID=84）
    const findCarRentCategory = (categories: any[]): number | null => {
      for (const category of categories) {
        if (category.id === 84) {
          return 84
        }
        if (category.children && category.children.length > 0) {
          const found = findCarRentCategory(category.children)
          if (found) return found
        }
      }
      return null
    }

    const carRentCategoryId = findCarRentCategory(categoryList.value)
    if (carRentCategoryId) {
      formData.categoryId = carRentCategoryId
      console.log('✅ 自动设置默认分类为车辆出租，分类ID:', carRentCategoryId)
    } else {
      console.warn('⚠️ 未找到车辆出租分类（ID=84），请手动选择分类')
    }
  }

  // 获取商品品牌列表
  brandList.value = await ProductBrandApi.getSimpleBrandList()
  console.log('汽车商品添加页面 - 商品品牌列表加载完成，数量:', brandList.value.length)
})
</script>
